//
//  TransferTaskViewController.m
//  YuTang
//
//  Created by 葛悦彣 on 2024/8/20.
//

#import "TransferTaskViewController.h"
#import "CancelTaskHeaderView.h"
#import "TransferTaskTableViewCell.h"
#import "CancelTaskFooterView.h"
#import "CancelAndTransferModel.h"
#import "PersonInCchargeShowView.h"
#import "YTSelectStringShowView.h"
#import "ExamineViewController.h"
@interface TransferTaskViewController ()
@property (nonatomic ,strong) CancelAndTransferModel * TJmodel;
@property (nonatomic ,strong) ClockModel * model;


@end

@implementation TransferTaskViewController
- (void)setModel:(ClockModel *)model{
    _model = model;
    self.TJmodel = [CancelAndTransferModel new];
    self.TJmodel.ID = self.ID;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    UIView * topview = [UIView new];
    topview.backgroundColor = KcolorHex(@"#0967FF");
    [self.view addSubview:topview];
    [topview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.right.offset(0);
        make.height.offset(Knav_HeightX);
    }];
    MJWeakSelf
    UIView * backview = [UIView new].addClickBlock(^{
        [weakSelf popViewController];
    });
    [topview addSubview:backview];
    [backview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.offset(44);
        make.left.bottom.offset(0);
        make.width.offset(kwt(120));
    }];
    
    UIImageView * leftimg = kimageView(@"white_path");
    [backview addSubview:leftimg];
    [leftimg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.height.offset(20);
        make.left.offset(kwt(10));
        make.centerY.offset(0);
    }];
    
    UILabel * leftlab = [DTKTool labelWithText:@"转交任务" andFont:kCFont(18) andTextColor:UIColor.whiteColor];
    [backview addSubview:leftlab];
    [leftlab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(kwt(43));
        make.centerY.offset(0);
    }];
    
    
    UIView * buttonview = [UIView new];
    buttonview.backgroundColor = UIColor.whiteColor;
    [self.view addSubview:buttonview];
    [buttonview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.offset(0);
        make.height.offset(kwt(63) + KSafeAreaBottomHeight);
    }];
    
    UIView * line = [UIView new];
    line.backgroundColor = KcolorHex(@"#ECECEC");
    [buttonview addSubview:line];
    [line mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.offset(0);
        make.height.offset(0.5);
    }];
    
    UIButton * qxbtn = [UIButton buttonWithType:UIButtonTypeCustom];
    qxbtn.backgroundColor = KcolorHex(@"#F0F2F4");
    [qxbtn setTitle:@"取消" forState:UIControlStateNormal];
    [qxbtn setTitleColor:KcolorHex(@"#5A6066") forState:UIControlStateNormal];
    qxbtn.titleLabel.font = kCFont(17);
    [DTKTool YJ:kwt(5) andView:qxbtn];
    [qxbtn addTarget:self action:@selector(leftBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [buttonview addSubview:qxbtn];
    [qxbtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.offset(kwt(48));
        make.width.offset(kwt(133));
        make.left.offset(kwt(15));
        make.top.offset(kwt(8));
    }];
    
    UIButton * qrbtn = [UIButton buttonWithType:UIButtonTypeCustom];
    qrbtn.backgroundColor = [UIColor gradientColorWithSize:CGSizeMake(kwt(195), 1) direction:GradientColorDirectionLevel startColor:KcolorHex(@"#2892FE") endColor:KcolorHex(@"#0366FE")];
    [qrbtn setTitle:@"提交" forState:UIControlStateNormal];
    [qrbtn setTitleColor:UIColor.whiteColor forState:UIControlStateNormal];
    qrbtn.titleLabel.font = kCFont(17);
    [DTKTool YJ:kwt(5) andView:qrbtn];
    [qrbtn addTarget:self action:@selector(rightBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [buttonview addSubview:qrbtn];
    [qrbtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.offset(kwt(48));
        make.width.offset(kwt(195));
        make.right.offset(kwt(-15));
        make.top.offset(kwt(8));
    }];
    
    [self.view addSubview:self.tableview];
    [self.tableview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.offset(0);
        make.top.equalTo(topview.mas_bottom);
        make.bottom.equalTo(buttonview.mas_top);
    }];
    
    
    [self loadNewData];
}
- (void)loadNewData{
    [self.view showBusyHUD];
    NSMutableDictionary * dict = [NSMutableDictionary dictionary];
    [dict setObject:self.ID forKey:@"id"];
    [SCNetManger PostCardDetailWithDict:dict andCompetionHandlerBlock:^(HTTPDicBase * model) {
        [self.view hideBusyHUD];
        if(model.code == 200){
            
            self.model = [ClockModel yy_modelWithDictionary:model.result];
            //            //数据处理 出来统一配置时多项选择
            //            if(self.model.configureItem > 0 ){///统一配置或者分别配置
            //                for (pondModelListModel * pondModel in self.model.pondModelList) {///鱼塘列表
            //                    for (TemplateFoundDetailsTaskItemModelListModel * itemModel in pondModel.taskItemModelList) {///任务列表
            //                        itemModel.configureItem = self.model.configureItem;
            //                    }
            //                }
            //            }
            [self.tableview reloadData];
        } else {
            [self.view showWarning:model.message];
        }
    }];
}



- (void)leftBtnClick{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)rightBtnClick{
    
    if([self.TJmodel ZJRWHudString].length > 0){
        [self.view showWarning:[self.TJmodel ZJRWHudString]];
        return;
    }
    [self.view showBusyHUD];
    NSMutableDictionary * dict = [self.TJmodel ZJRWDict];
    [dict setObject:@(self.type) forKey:@"type"];
    [dict setObject:self.userId forKey:@"userId"];
    [dict setObject:self.userName forKey:@"userName"];
    
    [SCNetManger PostTaskHandoverWithDict:dict  andCompetionHandlerBlock:^(HTTPDicBase * model) {
        [self.view hideBusyHUD];
        if(model.code == 200){
            [self.view showWarning:model.message];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                // 2秒后执行的代码
                [self.navigationController popToRootViewControllerAnimated:NO];
                ExamineViewController * vc = [ExamineViewController new];
                vc.hidesBottomBarWhenPushed = YES;
                [[DTKTool getCurrentVC].navigationController pushViewController:vc animated:YES];
            });
        } else {
            [self.view showWarning:model.message];
        }
    }];
}


-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    CancelTaskHeaderView * view = [CancelTaskHeaderView NewView];
    view.nameStr = @"转交内容";
    view.model = self.model;
    return view;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if(self.model.appointorName.length > 0){
        return self.model.HeaderTopView + kwt(50 + 8);
    }
    return self.model.HeaderTopView + kwt(60);
}


- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    MJWeakSelf
    CancelTaskFooterView * view = [CancelTaskFooterView NewView];
    view.VoiceBlock = ^(NSString * _Nonnull str) {
        weakSelf.TJmodel.voiceUrl = str;
        [weakSelf.tableview reloadData];
    };
    view.model = self.TJmodel;
    return view;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return kwt(63);
}

- (NSInteger)tableView:(nonnull UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return self.TJmodel.TransferCellH;
    
}
- (nonnull UITableViewCell *)tableView:(nonnull UITableView *)tableView cellForRowAtIndexPath:(nonnull NSIndexPath *)indexPath {
    MJWeakSelf
    TransferTaskTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"TransferTaskTableViewCell"];
    if (cell == nil) {
        cell = [[TransferTaskTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"TransferTaskTableViewCell"];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.model = self.TJmodel;
    cell.openYYBlock = ^(CancelAndTransferModel * _Nonnull model) {
        [weakSelf QXYYClick];
    };
    cell.openUserBlock = ^(CancelAndTransferModel * _Nonnull model) {
        [weakSelf openRWZPRWithModel:model];
    };
    cell.reLoadBlock = ^{
        [weakSelf.tableview reloadData];
    };
    return cell ;
}

- (void)QXYYClick{
    [self.view showBusyHUD];
    NSMutableDictionary * dict = [NSMutableDictionary dictionaryWithDictionary:@{@"dictCode":@"cancle_reason"}];
    [SCNetManger PostDictGetDictTextDict:dict andCompetionHandlerBlock:^(HTTPArrBase * model) {
        [self.view hideBusyHUD];
        if(model.code == 200){
            NSArray<getDictTextModel *> * array = [NSArray yy_modelArrayWithClass:getDictTextModel.class json:model.result];
            int index = 0;
            int i = 0;
            NSMutableArray * nameArray = [NSMutableArray array];
            for (getDictTextModel * gmodel in array) {
                if(gmodel.value.intValue == self.TJmodel.applyReasonCode){
                    index = i;
                }
                [nameArray addObject:gmodel.title];
                i++;
            }
            [YTSelectStringShowView showViewWithTitle:@"选择转交原因" andIndex:index andDateArray:nameArray andBlock:^(NSString * _Nonnull str) {
                for (getDictTextModel * gmodel in array) {
                    if([gmodel.title isEqualToString: str]){
                        self.TJmodel.applyReason = gmodel.title;
                        self.TJmodel.applyReasonCode = gmodel.value.intValue;
                        [self.tableview reloadData];
                        return;
                    }
                }
            }];
        } else {
            [self.view showWarning:model.message];
        }
    }];
}
- (void)openRWZPRWithModel:(CancelAndTransferModel *)Model{
    
    [self.view showBusyHUD];
    MJWeakSelf
    [SCNetManger PostGetPositionAndUserByOrgCodeWithDict: [NSMutableDictionary dictionary] andCompetionHandlerBlock:^(HTTPArrBase * model) {
        [self.view hideBusyHUD];
        if(model.code ==200){
            NSArray <PositionUserModel *>* modelarray = [NSArray yy_modelArrayWithClass:PositionUserModel.class json:model.result];
            
            MJWeakSelf
            [SearchPersonInCchargeShowView showviewWithTitle:@"转交人" andArray:modelarray andBlock:^(NSString * _Nonnull ID) {
                
                for (PositionUserModel * pmodel in modelarray) {
                    for (PondUserModel * userModel in pmodel.userModelList) {
                        if ([ID isEqualToString:userModel.userId]) {
                            weakSelf.TJmodel.tempUserModel = [NSMutableArray arrayWithArray:@[userModel]];
                            [weakSelf.tableview reloadData];
                            return;
                        }
                    }
                    
                }
            }];
        } else {
            [self.view showWarning:model.message];
        }
    }];
}
@end
